@echo off
:: Excel2User Docker Redeploy Script
:: Function: Automated Docker image rebuild and container redeployment

set IMAGE_NAME=excel2user
set CONTAINER_NAME=excel2user
set TEMP_IMAGE_NAME=%IMAGE_NAME%-temp

title Excel2User Docker Redeploy
echo ========================================
echo    Excel2User Docker Redeploy
echo ========================================
echo.

:: Check if Docker is running
docker version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Docker is not running or not installed. Please start Docker Desktop first.
    pause
    exit /b 1
)

echo --- Step 1: Building new temporary image: %TEMP_IMAGE_NAME% ---
docker build -t %TEMP_IMAGE_NAME% .
if %errorlevel% neq 0 (
    echo [ERROR] Docker image build failed!
    pause
    exit /b 1
)

echo.
echo --- Step 2: Stopping and removing existing container: %CONTAINER_NAME% ---
docker stop %CONTAINER_NAME% >nul 2>&1
docker rm %CONTAINER_NAME% >nul 2>&1
echo [INFO] Old container stopped and removed (if existed)

echo.
echo --- Step 3: Removing old image: %IMAGE_NAME% ---
docker rmi %IMAGE_NAME% >nul 2>&1
echo [INFO] Old image removed (if existed)

echo.
echo --- Step 4: Tagging temporary image to final name: %IMAGE_NAME% ---
docker tag %TEMP_IMAGE_NAME% %IMAGE_NAME%
docker rmi %TEMP_IMAGE_NAME%
echo [INFO] Image retagging completed

echo.
echo --- Step 5: Running new container: %CONTAINER_NAME% ---
docker run -d --name %CONTAINER_NAME% -p 7637:5000 %IMAGE_NAME%
if %errorlevel% neq 0 (
    echo [ERROR] Container startup failed!
    pause
    exit /b 1
)

echo.
echo ========================================
echo    Redeployment Complete!
echo ========================================
echo [INFO] Application URL: http://localhost:7637
echo [INFO] Admin Panel: http://localhost:7637/admin
echo [INFO] Default Account: admin / admin123
echo.
echo [TIP] Container management commands:
echo   View logs: docker logs %CONTAINER_NAME%
echo   Stop container: docker stop %CONTAINER_NAME%
echo   Restart container: docker restart %CONTAINER_NAME%
echo ========================================
pause